package com.example.servicegateway.filter;

import com.example.servicegateway.constants.AuthConstant;
import com.example.servicegateway.entity.TokenInfo;
import com.example.servicegateway.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Order
@Component
public class AuthGlobalFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst(AuthConstant.JWT_TOKEN_HEADER);
        log.info("请求url={}，进行AuthGlobalFilter过滤器处理", exchange.getRequest().getURI());
        if (StringUtils.isBlank(token)) {
            return chain.filter(exchange);
        }

        TokenInfo tokenInfo = TokenUtils.wrapper(token);
        //从token中解析用户信息并设置到Header中去
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header("userName", tokenInfo.getUserName())
                .header("userId", tokenInfo.getUserId())
                .build();
        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }
}
